package ext;

import org.junit.Test;

public class StringSubstract {
    
    public String substract(String a, String b) {
        int m = a.length(), n = b.length();
        if (m < n || m == n && a.compareTo(b) < 0) { //保证a必须大于b
            String t = substract(b, a);
            return "-" + t;
        }
        char[] as = a.toCharArray(), bs = b.toCharArray();
        int flag = 0;
        StringBuilder sb = new StringBuilder();
        int cur;
        for (int i = 0; i < n; i++) {
            int ac = as[m - i - 1] - '0', bc = bs[n - i - 1] - '0';
            if (ac >= bc + flag) {
                cur = ac - bc - flag;
                flag = 0;
            } else {
                cur = ac + 10 - bc - flag;
                flag = 1;
            }
            sb.insert(0, cur);
        }

        for (int i = n; i < m; i++) {
            int ac = as[m - i - 1] - '0';
            if (ac >= flag) {
                cur = ac - flag;
                flag = 0;
            } else {
                cur = 10 + ac - flag;
                flag = 1;
            }
            sb.insert(0, cur);
        }
        cur = 0;
        while (cur < sb.length()) {
            if (sb.charAt(cur) == '0')  {
                cur++;
            } else {
                break;
            }
        }
        return sb.substring(cur);
    }

    @Test
    public void test() {
        String a = "11223", b = "1456";
        System.out.println(substract(a, b));
        System.out.println(Integer.parseInt(a) - Integer.parseInt(b));
    }

}